import Vue from 'vue'
import {
	login,
	logout,
	phoneLogin,
	thirdLogin,
	sLogin
} from "@/api/login"
import {
	ACCESS_TOKEN,
	USER_NAME,
	USER_INFO,
	USER_AUTH,
	SYS_BUTTON_AUTH,
	UI_CACHE_DB_DICT_DATA,
	TENANT_ID,
	CACHE_INCLUDED_ROUTES
} from "@/store/mutation-types"
import {
	welcome
} from "@/utils/util"
import {
	queryPermissionsByUser
} from '@/api/api'
import {
	getAction
} from '@/api/manage'

const user = {
	state: {
		token: '',
		username: '',
		realname: '',
		tenantid: '',
		welcome: '',
		avatar: '',
		permissionList: [],
		info: {}
	},

	mutations: {
		SET_TOKEN: (state, token) => {
			state.token = token
		},
		SET_NAME: (state, {
			username,
			realname,
			welcome
		}) => {
			state.username = username
			state.realname = realname
			state.welcome = welcome
		},
		SET_AVATAR: (state, avatar) => {
			state.avatar = avatar
		},
		SET_PERMISSIONLIST: (state, permissionList) => {
			state.permissionList = permissionList
		},
		SET_INFO: (state, info) => {
			state.info = info
		},
		SET_TENANT: (state, id) => {
			state.tenantid = id
		},
	},

	actions: {
		// CAS验证登录
		ValidateLogin({
			commit
		}, userInfo) {
			return new Promise((resolve, reject) => {
				getAction("/sys/cas/client/validateLogin", userInfo).then(response => {
					console.log("----cas 登录--------", response);
					if (response.success) {
						const result = response.result
						const userInfo = result.userInfo
						Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
						Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
						Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
						commit('SET_TOKEN', result.token)
						commit('SET_INFO', userInfo)
						commit('SET_NAME', {
							username: userInfo.username,
							realname: userInfo.realname,
							welcome: welcome()
						})
						commit('SET_AVATAR', userInfo.avatar)
						resolve(response)
					} else {
						resolve(response)
					}
				}).catch(error => {
					reject(error)
				})
			})
		},
		// 登录
		Login({
			commit
		}, userInfo) {
			return new Promise((resolve, reject) => {
				if (userInfo.appId == null || userInfo.appId == '') {
					userInfo.appId = window._CONFIG['domianAppId'];
				}
				sLogin(userInfo).then(response => {
					if (response.code == '200') {
						window.localStorage.setItem('response',JSON.stringify(response))
						const result = response.result
						const userInfo = result.userInfo
						Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
						Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
						Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
						Vue.ls.set(UI_CACHE_DB_DICT_DATA, result.sysAllDictItems, 7 * 24 * 60 * 60 * 1000)
						// commit('SET_TOKEN', result.token)
						// commit('SET_INFO', userInfo)
						// commit('SET_NAME', { username: userInfo.username,realname: userInfo.realname, welcome: welcome() })
						// commit('SET_AVATAR', userInfo.avatar)
						window.sessionStorage.setItem('load', JSON.stringify(response.result.sysAllDictItems))
						window.sessionStorage.setItem('menu', JSON.stringify(response.result.menuList))
						window.sessionStorage.setItem('manage', JSON.stringify(response.result.manageList))
						window.sessionStorage.setItem('role', JSON.stringify(response.result.roleList))
						window.sessionStorage.setItem('userInfo', JSON.stringify(response.result.userInfo))
						window.sessionStorage.setItem('token',response.result.token),
						window.sessionStorage.setItem('appId','78eb6f51fbd44297a528e6b01bbe72cf'),
						window.localStorage.setItem('load', JSON.stringify(response.result.sysAllDictItems))
						window.localStorage.setItem('menu', JSON.stringify(response.result.menuList))
						window.localStorage.setItem('manage', JSON.stringify(response.result.manageList))
						window.localStorage.setItem('role', JSON.stringify(response.result.roleList))
						window.localStorage.setItem('userInfo', JSON.stringify(response.result.userInfo))
						window.localStorage.setItem('token',response.result.token),
						resolve(response)
					} else {
						reject(response)
					}
				}).catch(error => {
					reject(error)
				})
			})
		},
		//手机号登录
		PhoneLogin({
			commit
		}, userInfo) {
			return new Promise((resolve, reject) => {
				phoneLogin(userInfo).then(response => {
					if (response.code == '200') {
						const result = response.result
						const userInfo = result.userInfo
						Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
						Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
						Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
						Vue.ls.set(UI_CACHE_DB_DICT_DATA, result.sysAllDictItems, 7 * 24 * 60 * 60 *
							1000)
						commit('SET_TOKEN', result.token)
						commit('SET_INFO', userInfo)
						commit('SET_NAME', {
							username: userInfo.username,
							realname: userInfo.realname,
							welcome: welcome()
						})
						commit('SET_AVATAR', userInfo.avatar)
						resolve(response)
					} else {
						reject(response)
					}
				}).catch(error => {
					reject(error)
				})
			})
		},
		// 获取用户信息
		GetPermissionList({
			commit
		}) {
			window.localStorage.getItem('token')
			var token = window.localStorage.getItem('token')
			console.log(token)
			var url = 'http://172.16.20.40:8080/student/#'
			return new Promise((resolve, reject) => {
				// queryPermissionsByUser().then(response => {
				let response = {
					'success': true,
					'message': '查询成功',
					'code': 200,
					'result': {
						'allAuth': [{
							'action': 'online:goGenerateCode',
							'describe': '代码生成按钮',
							'type': '1',
							'status': '1'
						}, {
							'action': 'user:add',
							'describe': '添加按钮',
							'type': '1',
							'status': '1'
						}, {
							'action': 'user:edit',
							'describe': '用户编辑',
							'type': '1',
							'status': '1'
						}, {
							'action': 'user:sex',
							'describe': '表单性别可见',
							'type': '1',
							'status': '1'
						}, {
							'action': 'user:form:birthday',
							'describe': '禁用生日字段',
							'type': '2',
							'status': '1'
						}, {
							'action': 'user:form:phone',
							'describe': '手机号禁用',
							'type': '2',
							'status': '1'
						}],
						'auth': [{
							'action': 'user:edit',
							'describe': '用户编辑',
							'type': '1'
						}, {
							'action': 'user:form:phone',
							'describe': '手机号禁用',
							'type': '2'
						}, {
							'action': 'user:sex',
							'describe': '表单性别可见',
							'type': '1'
						}, {
							'action': 'user:add',
							'describe': '添加按钮',
							'type': '1'
						}, {
							'action': 'user:form:birthday',
							'describe': '禁用生日字段',
							'type': '2'
						}, {
							'action': 'online:goGenerateCode',
							'describe': '代码生成按钮',
							'type': '1'
						}],
						'menu': [
						  {
						    'redirect': null,
						    'path': '/dashboard/analysis',
						    'component': 'dashboard/Analysis',
						    'route': '1',
						    'meta': {
						      'keepAlive': false,
						      'internalOrExternal': false,
						      'icon': 'home',
						      'componentName': 'Analysis',
						      'title': '首页'
						    },
						    'name': 'dashboard-analysis',
						    'id': '9502685863ab87f0ad1134142788a385'
						  },
						]
					},
					'timestamp': 1622270623470
				}

				const menuData = response.result.menu
				const authData = response.result.auth
				const allAuthData = response.result.allAuth

				//Vue.ls.set(USER_AUTH,authData);
				sessionStorage.setItem(USER_AUTH, JSON.stringify(authData))
				sessionStorage.setItem(SYS_BUTTON_AUTH, JSON.stringify(allAuthData))
				if (menuData && menuData.length > 0) {
					//update--begin--autor:qinfeng-----date:20200109------for：edu-63 一级菜单的子菜单全部是隐藏路由，则一级菜单不显示------
					menuData.forEach((item, index) => {
						if (item['children']) {
							let hasChildrenMenu = item['children'].filter((i) => {
								return !i.hidden || i.hidden == false
							})
							if (hasChildrenMenu == null || hasChildrenMenu.length == 0) {
								item['hidden'] = true
							}
						}
					})
					//console.log(" menu show json ", menuData)
					//update--end--autor:qinfeng-----date:20200109------for：edu-63 一级菜单的子菜单全部是隐藏路由，则一级菜单不显示------
					commit('SET_PERMISSIONLIST', menuData)
				} else {
					reject('getPermissionList: permissions must be a non-null array !')
				}
				resolve(response)
				// }).catch(error => {
				//   reject(error)
				// })
			})
		},

		// 登出
		Logout({
			commit,
			state
		}) {
			return new Promise((resolve) => {
				commit('SET_TOKEN', '')
				commit('SET_PERMISSIONLIST', [])
				Vue.ls.remove(ACCESS_TOKEN)
				Vue.ls.remove(UI_CACHE_DB_DICT_DATA)
				Vue.ls.remove(CACHE_INCLUDED_ROUTES)
				let logoutToken = window.sessionStorage.getItem('token')
				//console.log('logoutToken: '+ logoutToken)
				logout(logoutToken).then(() => {
					if (process.env.VUE_APP_SSO == 'true') {
						window.sessionStorage.removeItem('appId')
						window.sessionStorage.removeItem('token')
						let sevice = 'http://' + window.location.host + '/'
						let serviceUrl = encodeURIComponent(sevice)
						window.location.href = process.env.VUE_APP_CAS_BASE_URL +
							'/logout?service=' + serviceUrl
					}
					resolve()
				}).catch(() => {
					resolve()
				})
			})
		},
		// 第三方登录
		ThirdLogin({
			commit
		}, param) {
			return new Promise((resolve, reject) => {
				thirdLogin(param.token, param.thirdType).then(response => {
					if (response.code == '200') {
						const result = response.result
						const userInfo = result.userInfo
						Vue.ls.set(ACCESS_TOKEN, result.token, 7 * 24 * 60 * 60 * 1000)
						Vue.ls.set(USER_NAME, userInfo.username, 7 * 24 * 60 * 60 * 1000)
						Vue.ls.set(USER_INFO, userInfo, 7 * 24 * 60 * 60 * 1000)
						commit('SET_TOKEN', result.token)
						commit('SET_INFO', userInfo)
						commit('SET_NAME', {
							username: userInfo.username,
							realname: userInfo.realname,
							welcome: welcome()
						})
						commit('SET_AVATAR', userInfo.avatar)
						resolve(response)
					} else {
						reject(response)
					}
				}).catch(error => {
					reject(error)
				})
			})
		},
		saveTenant({
			commit
		}, id) {
			Vue.ls.set(TENANT_ID, id, 7 * 24 * 60 * 60 * 1000)
			commit('SET_TENANT', id)
		}


	}
}

export default user
